module.exports = function handleAddMethods(module_config, add_page) {

  var methodsCodeFirst = "";

  //输入变量
  var formDataParams = `    `;  //表单参数，用于提交编辑

  for (var itemKey in add_page) {
    var item = add_page[itemKey];
    if (itemKey == 'formData') {
      for (var inputItemKey in item) {
        if (inputItemKey == 'titleText') continue;
        if (inputItemKey.includes('date')) {
          var { dateConfig } = item[inputItemKey];
          formDataParams += `
              ${dateConfig.startDateName},
              ${dateConfig.endDateName},
            `;
          continue;
        }
        formDataParams += `` + item[inputItemKey].inputName + `,
        `;
      }
    }
  }

  var jumpPathAdd = add_page.addBtn.jumpPath;
  var jumpPathEdit = add_page.editBtn.jumpPath;

  //添加或编辑成功后跳转的页面
  var jumpPath = "/"; //添加成功后跳转的路由
  var index = "";
  if (add_page.add_page_name) {
    for (var itemKey in module_config) {
      var itemVal = module_config[itemKey];
      if (itemKey.includes('add_page') && itemKey != 'add_page') {
        if (add_page.add_page_name == itemVal.add_page_name) {
          index = itemKey.slice(8,);
        }
      }
    }
    jumpPath = `/${module_config.module_name}_${module_config['table' + index].table_name || 'table'}`
  } else {
    jumpPath = `/${module_config.module_name}_table`;
  }


  //非空校验模板判断 新增编辑字段保持一致
  var enableNullObj = handleEnableNullStr({
    add_page,
  });
  var enableNullFormData = enableNullObj.enableNullFormData;  //非空参数展示
  var enableNullFormDataStr = enableNullObj.enableNullFormDataStr;  //非空校验代码，已配置

  var methodsCodeFirst = "";
  var methodsCodeSecond = "";
  var mountedCode = "";

  //额外的请求
  var extraMethodsObj = getExtraRequestObj(add_page);
  var {
    firstExtraMethods,
    secondExtraMethods,
    extraMountedCode
  } = extraMethodsObj;

  methodsCodeFirst += firstExtraMethods;
  methodsCodeSecond += secondExtraMethods;
  mountedCode += extraMountedCode;

  //添加方法集合 First类


  var dateMethodsStr = ""; //日期方法
  //输入项的方法的创建
  for (var itemKey in add_page) {
    if (itemKey == 'formData') {
      var formDataItem = add_page[itemKey];
      for (var inputItemKey in formDataItem) {
        var inputItem = formDataItem[inputItemKey];
        //日期方法
        if (inputItemKey.includes('date')) {
          var {
            labelName,
            dateConfig,
          } = inputItem;
          dateMethodsStr += `
          //日期选择
          ${dateConfig.dateChangeMethodsName} (dateArr, startDate, endDate) {
            this.formData.${dateConfig.startDateName} = startDate;
            this.formData.${dateConfig.endDateName} = endDate;
          },
        `;
        }
        //
      }
    }
  }
  methodsCodeFirst += dateMethodsStr;

  //添加方法
  var addMethods = getAddMethods({
    url: add_page.addBtn.url,
    params: formDataParams,
    enableNullFormDataStr,
    jumpPath: jumpPathAdd ? jumpPathAdd : jumpPath,
    extraParams: add_page.addBtn.extraParams,
    submitCheckCode: add_page.submitCheckCode,
    extraQueryParams: add_page.addBtn.extraQueryParams, //跳转时携带的参数
  });
  methodsCodeFirst += addMethods;


  //编辑详情
  var editMethods = "";
  editMethods += getEditDetailMethods({
    url: add_page.editBtn.detailUrl,
    detailParams: add_page.editBtn.detailParams,
    detailType: add_page.editBtn.detailType,
    isSplitSearchString: add_page.editBtn.isSplitSearchString,
    detailDataFormatCode: add_page.editBtn.detailDataFormatCode, //详情格式化代码
    add_page_config: add_page,
  });

  //编辑方法
  editMethods += getEditSubmitMethods({
    url: add_page.editBtn.editUrl,
    params: formDataParams,
    enableNullFormDataStr,
    jumpPath: jumpPathEdit ? jumpPathEdit : jumpPath,
    isSplitSearchString: add_page.editBtn.isSplitSearchString,
    extraParams: add_page.editBtn.extraParams,
    submitCheckCode: add_page.submitCheckCode,
    extraQueryParams: add_page.editBtn.extraQueryParams, //跳转时携带的参数
  })
  methodsCodeFirst += editMethods;

  var uploadMethodsStr = ``;
  var bgEditorStr = ``;
  for (var itemKey in add_page) {
    var item = add_page[itemKey];
    if (itemKey == 'formData') {
      for (var inputItemKey in item) {
        if (inputItemKey.includes('uploadImg')) {
          var { uploadMethod, inputName } = item[inputItemKey];
          uploadMethodsStr += `
            //图片上传
            ${uploadMethod} (imgArrStr) {
              this.formData.${inputName} = imgArrStr;
            },
          `;
        } else if (inputItemKey.includes('richText')) {
          var { labelName, inputName, minHeight, editContentChangeMethodName } = item[inputItemKey];
          bgEditorStr += `
            //富文本编辑器
            ${editContentChangeMethodName} (bgEditorStr) {
              var textColor = "#f9e7d8";
              var isGet = /;;; (.*?) ;;;/.test(bgEditorStr);
              var textStr = "";
              if(!isGet) {
                textStr = \`
                <div style=";;; color: \${textColor}; padding: 10px; ;;;"> 
                \${bgEditorStr} </div>\`.replace(/;;; (.*?) ;;;/g, (node, key)=> {
                  return \`;;; text-indent: 2em!important; color: \${textColor}; padding: 10px; ;;;\`;
                })
              } else {
                textStr = bgEditorStr.replace(/;;;(.*?);;;/g, (node, key)=> {
                  return \`;;; text-indent: 2em!important; color: \${textColor}; padding: 10px; ;;;\`;
                })
              }
              this.formData.${inputName} = textStr;
            },
          `;
        }
      }
    }
  }
  methodsCodeFirst += uploadMethodsStr;
  methodsCodeFirst += bgEditorStr;

  return {
    methodsCodeFirst,
    methodsCodeSecond,
    mountedCode
  };
}


//获取日期添加方法
function getDateMethods(searchItemObj) {
  var dateChangeMethodsName =
    searchItemObj.dateChangeMethodsName
      ? searchItemObj.dateChangeMethodsName
      : 'handleDateChange';

  tSearchTpl += dateSearchTpl({
    labelName: searchItemObj.labelName,
    dateChangeMethodsName: searchItemObj.dateConfig.dateChangeMethodsName, //日期的作用描述，用于区分多个日期
  });

  formDataContent += `
 ${searchItemObj.dateConfig.startDateName}: "",
 ${searchItemObj.dateConfig.endDateName}: "",
 `;


  dateMethodsContent += `
 //日期选择
 ${searchItemObj.dateConfig.dateChangeMethodsName} (dateArr, startDate, endDate) {
   this.formData.${searchItemObj.dateConfig.startDateName} = startDate;
   this.formData.${searchItemObj.dateConfig.endDateName} = endDate;
 },
`;
}

//额外的方法拼接
function getExtraRequestObj(add_page) {
  var firstExtraMethods = "";
  var secondExtraMethods = "";
  var extraMountedCode = "";
  //data
  //mounted
  //methods 拆分成两个部分
  for (var itemKey in add_page.extraRequest) {
    if (itemKey == 'methodsCode') {
      var extraItem = add_page.extraRequest['methodsCode'];
      extraItem.forEach((item, index) => {
        if (item.type.includes("opts")) {
          extraMountedCode += `
            this.${item.methodName}(); //${item.explainText}
          `;

          firstExtraMethods += `
            //${item.explainText}
            ${item.methodName} () {
              this.allMethods.${item.methodName}();
            },
            `;

          secondExtraMethods += `
            //${item.explainText}
            ${item.methodName} () {
              var url = ${item.api};
              var data =${item.params};
              console.log("参数", data);
              jhTools.post(
                url,
                data,
                null,
                (res) => {
                  console.log("结果", res);
                  if (res.code == 200) {
                    var opts = _this.${item.optsName} ? _this.${item.optsName} : [];
                    res.data.records.forEach((item, index) => {
                      opts.push({
                        label: item.${item.optsConfig.label} + "",
                        value: item.${item.optsConfig.value} + "",
                      })
                    });
                    _this.${item.optsName} = opts;
                    
                  } else {
                    _this.$message({
                      type: "warning",
                      message: res.message,
                    });
                  }
                },
                (err) => {
                  console.log(err);
                }
              );
            },
            `;
        }
      })
    }
  }

  return {
    firstExtraMethods,
    secondExtraMethods,
    extraMountedCode
  }
}


//返回非空校验方法
function handleEnableNullStr(opt) {
  var enableNullFormData = "",
    add_page = opt.add_page,
    enableNullFormDataTipsObj = "";
  for (var itemKey in add_page.formData) {
    if (itemKey == 'titleText') continue;
    var item = add_page.formData[itemKey];
    // console.log(item);
    if (item.isNeed == 'true') {
      if (itemKey.includes('date')) {
        enableNullFormData += `
          "${item.dateConfig.startDateName}",
          "${item.dateConfig.endDateName}",
        `;
        enableNullFormDataTipsObj += `
          "${item.dateConfig.startDateName}": "开始${item.labelName}",
          "${item.dateConfig.endDateName}": "结束${item.labelName}",
        `;
        continue;
      }
      enableNullFormData += `"${item.inputName}",
        `;
      enableNullFormDataTipsObj += `"${item.inputName}": "${item.labelName}",
        `;
    }
  }
  var enableNullFormDataStr = `
  //非空校验
  var dataRes = jhTools.checkInputFormDataTool({
    tThis: this,
    dataArr: [
      ${enableNullFormData}
    ],
    tipsObj: {
      ${enableNullFormDataTipsObj}
    }
  });
  if(!dataRes) {
    return;
  }
  `;
  return {
    enableNullFormData, //返回字符串形式的数据
    enableNullFormDataStr,  //返回整个非空校验方法
  }
}


//添加方法
function getAddMethods(opt) {
  var url = opt.url,
    params = opt.params,
    enableNullFormDataStr = opt.enableNullFormDataStr,
    jumpPath = opt.jumpPath ? opt.jumpPath : '/index',
    extraParams = opt.extraParams ? opt.extraParams : "",
    submitCheckCode = opt.submitCheckCode ? opt.submitCheckCode : "",
    extraQueryParams = opt.extraQueryParams ? opt.extraQueryParams : "{}";
  return `
    //添加
    handleAdd () {
      let url = ${url};
      ${enableNullFormDataStr}
      ${submitCheckCode}
      var {
        ${params}
      } = this.formData;

      let data = {
        ${params}
        ${extraParams}
      };
     
      console.log("参数", data);
      jhTools.post(
        url,
        data,
        null,
        (res) => {
          console.log("结果", res);
          if (res.code == "200") {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.$router.push({
              path: "${jumpPath}",
              query: ${extraQueryParams}
            });
          } else {
            this.$message({
              type: "warning",
              message: res.message,
            });
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
  `;
}

//获取编辑数据
function getEditDetailMethods(opt) {
  var url = opt.url,  //详情url
    detailParams = opt.detailParams,
    detailType = opt.detailType ? opt.detailType : 'get',
    isSplitSearchString = opt.isSplitSearchString ? opt.isSplitSearchString : "",
    detailDataFormatCode = opt.detailDataFormatCode ? opt.detailDataFormatCode : "",
    add_page_config = opt.add_page_config ? opt.add_page_config : "{}";
  if (isSplitSearchString == 'true') {
    url = url + ` + "?id=" + id`;
  }
  //详情请求的额外参数
  var params = ``;
  if (detailParams) {
    for (var key in detailParams) {
      var val = detailParams[key];
      params += `${key}: ${val}`
    }
  }
  //所有展示字段的赋值
  var showDataStr = `
    let formData = {};
  `;
  for (var itemKey in add_page_config.formData) {
    if (itemKey == 'titleText') continue; //标题说明跳出
    if (itemKey.includes('date')) {
      var { dateConfig } = add_page_config.formData[itemKey];
      showDataStr += `
          formData.${dateConfig.startDateName} = res.data.${dateConfig.startDateName} ? res.data.${dateConfig.startDateName} + "" : "",
          formData.${dateConfig.endDateName} = res.data.${dateConfig.startDateName} ? res.data.${dateConfig.endDateName} + "" : "",
        `;
      continue;
    }
    var inputName = add_page_config.formData[itemKey].inputName;
    showDataStr += `formData.${inputName} = res.data.${inputName} ? res.data.${inputName} + "" : "";
    `;
  }
  //遍历所有输入项的变量名, 放到请求方法中
  return `
  //获取数据
  getEditData(id) {
    let url = ${url}; 
    const param = {
      id,
      ${params}
    };
    console.log("详情", param);
    jhTools.${detailType}(
      url,
      param,
      null,
      (res) => {
        console.log("获取数据详情", res);
        if(res.code == 200) {
          ${showDataStr}
          ${detailDataFormatCode}

          this.formData = formData;
          setTimeout(()=> {
            this.showPageKey = 110;  //更新视图
          }, 300);
        }
      },
      (err) => {
        console.log(err);
      }
    );
  },
  `;
}


//编辑提交
function getEditSubmitMethods(opt) {
  var url = opt.url,
    params = opt.params,
    enableNullFormDataStr = opt.enableNullFormDataStr,
    jumpPath = opt.jumpPath ? opt.jumpPath : '/index',
    extraParams = opt.extraParams ? opt.extraParams : "",
    submitCheckCode = opt.submitCheckCode ? opt.submitCheckCode : "",
    extraQueryParams = opt.extraQueryParams ? opt.extraQueryParams : "{}";
  return `
    //编辑提交
    handleEdit () {

      ${enableNullFormDataStr}
      ${submitCheckCode}

      let url = ${url}
      let id = this.$route.query.id;
      
      var {
        ${params}
      } = this.formData;

      let data = { 
        id,
        ${params}
        ${extraParams}
       };
      console.log("参数", data);
      jhTools.post(
        url,
        data,
        null,
        (res) => {
          console.log("结果", res);
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.$router.push({
              path: "${jumpPath}",
              query: ${extraQueryParams}
            });
          } else {
            //提示
            this.$message({
              type: "warning",
              message: res.message,
            });
          }
          
        },
        (err) => {
          console.log(err);
        }
      );
    },
  `
}



